<template>
  <el-card>
    <div class="head-container">
      <el-input
        v-model="searchText"
        placeholder="请输入"
        clearable
        size="small"
        prefix-icon="el-icon-search"
        style="margin-bottom: 20px"
      />
    </div>
    <div>
      <el-radio-group v-model="seltype" size="small">
        <el-radio-button label="river">水源地类型</el-radio-button>
        <el-radio-button label="region">行政区划</el-radio-button>
      </el-radio-group>
    </div>
    <div class="head-container">
      <el-tree
        :data="deptOptions"
        :props="defaultProps"
        :expand-on-click-node="false"
        :filter-node-method="filterNode"
        default-expand-all
        ref="tree"
        node-key="id"
        highlight-current
        show-checkbox
        @check="handleCheckChange"
        @node-click="handleNodeClick"
      />
    </div>
  </el-card>
</template>

<script>
import { getRiverSegmentTree, getDistrictTree } from "@/api/commonApi";

export default {
  name: "TreeSelect",
  data() {
    return {
      searchText: "",
      seltype: "river",
      deptOptions: [],
      defaultProps: {
        children: "children",
        label: "label",
      },
      treeDataLoaded: false,
      allLeafIds: [], // 存储所有叶子节点ID
    };
  },
  watch: {
    searchText(val) {
      this.$refs.tree.filter(val);
    },
    seltype: {
      handler(newVal) {
        if (newVal === "river") {
          this.getSydTree();
        } else if (newVal === "region") {
          this.getRiverRegin();
        }
      },
      immediate: true,
    },
  },
  methods: {
    filterNode(value, data) {
      if (!value) return true;
      return data.label.indexOf(value) !== -1;
    },

    convertToTree(data) {
      const nodeMap = {};
      data.forEach((node) => {
        nodeMap[node.id] = {
          ...node,
          label: node.name,
          children: [],
        };
      });

      const tree = [];
      data.forEach((node) => {
        const currentNode = nodeMap[node.id];
        const parentId =
          node.pId === null || node.pId === undefined ? "0" : node.pId;
        const parentNode = nodeMap[parentId];

        if (parentNode) {
          parentNode.children.push(currentNode);
        } else {
          tree.push(currentNode);
        }
      });

      return tree;
    },

    // 递归收集所有叶子节点ID
    collectLeafIds(nodes, leafIds = []) {
      nodes.forEach((node) => {
        if (node.children && node.children.length > 0) {
          // 非叶子节点，递归处理子节点
          this.collectLeafIds(node.children, leafIds);
        } else {
          // 叶子节点，收集ID
          leafIds.push(node.id);
        }
      });
      return leafIds;
    },

    getSydTree() {
      const query = {
        segmentType: "IsAuto",
        segmentTypeDrink: "show",
      };
      getRiverSegmentTree(query).then((res) => {
        if (res.code === 200) {
          this.deptOptions = this.convertToTree(res.data || []);
          // 收集所有叶子节点ID
          this.allLeafIds = this.collectLeafIds(this.deptOptions);
          this.treeDataLoaded = true;
          this.$nextTick(() => this.setDefaultCheckedNode());
        }
      });
    },

    getRiverRegin() {
      const query = {
        segmentTypeDrink: "show",
        segmentType: "IsAuto",
      };
      getDistrictTree(query).then((res) => {
        if (res.code === 200) {
          this.deptOptions = this.convertToTree(res.data || []);
          // 收集所有叶子节点ID
          this.allLeafIds = this.collectLeafIds(this.deptOptions);
          this.treeDataLoaded = true;
          this.$nextTick(() => this.setDefaultCheckedNode());
        }
      });
    },

    // 默认选中所有叶子节点
    setDefaultCheckedNode() {
      const tree = this.$refs.tree;
      if (!tree || this.allLeafIds.length === 0) return;

      // 选中所有叶子节点
      tree.setCheckedKeys(this.allLeafIds);
      // 触发一次选中事件，同步初始选中状态
      this.handleCheckChange(this.allLeafIds);
    },

    // 处理节点点击（可选，保持原有点击逻辑）
    handleNodeClick(data) {
      console.log("点击的节点数据：", data);
    },

    // 处理选中状态变化
    handleCheckChange(checkedKeys, checkedNodes) {
      // 过滤出所有选中的叶子节点ID
      const checkedLeafIds = checkedKeys.filter((id) => {
        // 找到对应的节点
        const node = this.findNodeById(this.deptOptions, id);
        // 叶子节点判断：没有子节点或子节点为空
        return !node || (node.children && node.children.length === 0);
      });

      console.log("当前选中的叶子节点ID：", checkedLeafIds);
      // 对外发射选中的叶子节点ID
      this.$emit("treeCheckChange", checkedLeafIds);
    },

    // 辅助方法：根据ID查找节点
    findNodeById(nodes, id) {
      for (const node of nodes) {
        if (node.id === id) {
          return node;
        }
        if (node.children && node.children.length > 0) {
          const found = this.findNodeById(node.children, id);
          if (found) return found;
        }
      }
      return null;
    },
  },
};
</script>

<style>
/* 可选：调整复选框样式 */
.el-tree .el-tree-node__content .el-checkbox {
  margin-right: 8px;
}
</style>
